import socket  
import struct
import time

def buildframe1(frame_str):
    word = frame_str.split(' ')
    frame_list = []
    for i in word:
        if i.strip()!="":
            a=int(i,16)
            frame_list.append(a)
    return frame_list

def buildframe2(frame_str):
    str_len = len(frame_str)
    frame_list = []
    for i in range(str_len/2):
        a=int(frame_str[i+i:i+i+2],16)
        frame_list.append(a)
    return frame_list

def sendframe1(frame_str):
    frame_list = buildframe1(frame_str)
    for byte in frame_list:
        ss.send(struct.pack('B', byte))  

def sendframe2(frame_str):
    frame_list = buildframe2(frame_str)
    for byte in frame_list:
        ss.send(struct.pack('B', byte))

def showbuf(frame):
    frame_len = len(frame)
    frame_format = '%dB' % frame_len
    aa = struct.unpack(frame_format, frame)
    print frame_len, '->',
    for a in aa:
        print hex(a), ' ',
    print ''
    

print 'start'  
address = ('', 2020)  
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(address)
s.listen(5)  
  
ss, addr = s.accept()  
print 'got connected from',addr  

while (1):
      
    frame = ss.recv(512)
    showbuf(frame)
    sendframe1('02 4F 4B 0D 02 A5 01 10 04 94 B1 5B 00 5C 0D')
    
    frame = ss.recv(512)
    showbuf(frame)
    sendframe1('02 4F 4B 0D 02 A5 10 10 04 94 B1 5B 00 6B 0D')

    frame = ss.recv(512)
    showbuf(frame)
    sendframe1('03 4F 4B 0D 03 AA 01 10 04 F5 FF 39 00 EF 0D')

    frame = ss.recv(512)
    showbuf(frame)
    sendframe1('03 4F 4B 0D 03 AA 10 10 04 33 3D 00 00 41 0D')
    
    frame = ss.recv(512)
    showbuf(frame)
    sendframe1('04 4F 4B 0D 04 AA 10 10 04 F5 FF 39 00 EF 0D')

    frame = ss.recv(512)
    showbuf(frame)
    sendframe1('04 4F 4B 0D 04 AA 10 10 04 33 3D 00 00 41 0D')
        
time.sleep(10) 
ss.close()  
s.close()

print 'end'